<template>
    <div id='' class='my_tree'>
        <div class="ivu-p-8">
            <Input v-model="query" search placeholder="输入部门名称搜索" @on-change="handleSearch" />
        </div>
        <div class="content">
            <Tree :data="menuList" check-strictly @on-select-change="handleSelectNode" @on-contextmenu="handleContextMenu">
                <template slot="contextMenu">
                    <DropdownItem @click.native="addMenu">添加子部门</DropdownItem>
                    <DropdownItem divided @click.native="nodeDelete" style="color: #ed4014">删除</DropdownItem>
                </template>
            </Tree>
        </div>
    </div>
</template>
<script>
import { mapActions, mapState, mapGetters } from 'vuex'
export default {
    name: '',
    inject: ['provideClick'],
    props: [''],
    data() {
        return {
            menuList: [],
            menuListCopy: [],
            query: '',
        };
    },
    components: {},
    computed: {
        ...mapState('extend/sysDepartment', ['$row'])
    },
    beforeMount() { },
    mounted() {
        this.getTree()
    },
    methods: {
        ...mapActions('extend/sysDepartment', ['setData']),
        ...mapGetters('extend/sysDepartment', ['getData']),
        getTree() {
            this.setData([{
                key: '$row',
                value: null
            }])
            this.$http.$get('deptTopTree', { params: {} }).then(res => {
                if (res.code == 200) {
                    this.menuListCopy = icu.util.deepClone(this.recurrenceTree(res.data[0].children))
                    this.menuList = this.recurrenceTree(res.data[0].children);
                }
            })
        },
        recurrenceTree(data) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                element['title'] = element.title
                element['value'] = element.id
                element['expand'] = true
                element['contextmenu'] = true
                if (element.children) {
                    if (element.children.length !== 0) {
                        this.recurrenceTree(element.children)
                    }
                }
            }
            return data
        },
        // 延展收起树
        togTree(event) {
            this.toggleTree(this.menuListCopy, event)
            this.menuList = this.menuListCopy
        },
        toggleTree(data, event) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                element['expand'] = event
                if (element.children.length !== 0) {
                    this.toggleTree(element.children, event)
                }
            }
        },
        // 查询方法
        handleSearch() {
            const query = this.query;
            this.selectedData = [];
            if (query) {
                this.menuList = this.handleQueryNode(this.menuListCopy, query, []);
            } else {
                this.handleInitMenuList();
            }
        },
        handleInitMenuList() {
            this.menuList = this.menuListCopy
        },
        handleQueryNode(menuList, query, queryList) {
            menuList.forEach(menu => {
                let newMenu = {};
                for (let i in menu) {
                    if (i !== 'children') newMenu[i] = menu[i];
                }
                if (newMenu.title.indexOf(query) > -1) queryList.push(newMenu);
                if (menu.children && menu.children.length) newMenu.children = [];
                menu.children && this.handleQueryNode(menu.children, query, queryList);
            });
            return queryList;
        },
        // 点击树节点触发
        handleSelectNode(item) {
            this.provideClick("编辑", { prop: item })
        },
        // 当前节点点击右键时触发
        handleContextMenu(item) {
            this.setData([{
                key: "$row",
                value: item
            }])
        },
        // 新增菜单
        addMenu() {
            this.provideClick("右键新增", { prop: this.$row })
        },
        // 删除
        nodeDelete() {
            this.$Modal.confirm({
                title: '关闭确认',
                content: `您确认要删除菜单<strong>${this.$row.title}</strong>吗？`,
                onOk: () => {
                    this.$http.$post('deptRemove', { data: [this.$row.id] }).then(res => {
                        if (res.code == 200) {
                            this.$Message.success('删除成功');
                            this.getTree()
                        }else{
                            this.$Message.error(res.msg);
                        }
                    })
                }
            });
        },
        // 前台添加节点
        addNode() {
            let data = this.updateNode(this.menuListCopy)
            if (!this.query) {
                this.updateNode(this.menuList)
            } else {
                this.handleSearch()
            }
        },
        updateNode(data) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                // 根据$row定位添加的位置
                if (element.id == this.$row.id) {
                    let resD = this.getData()('respondData')
                    resD['title'] = resD.name
                    resD['value'] = resD.id
                    if (!element.children) {
                        element.children = [];
                    }
                    if (element.children.length == 0) {
                        element.children.push(resD)
                    } else {
                        // 然后根据respondData，添加到数组的指定位置，根据排序添加
                        element.children.push(resD)
                        element.children = element.children.sort(function (a, b) {
                            return a.sort * 1 - b.sort * 1;
                        })
                        // element.children.splice(element.sort * 1, 0, resD)
                    }
                    return
                }
                if (element.children.length !== 0) {
                    this.updateNode(element.children)
                }
            }
            return data
        },
    },
    watch: {}
}
</script>
<style>
.my_tree .ivu-tree-title {
    width: 98%;
}
</style>
<style lang='less' scoped>
.my_tree .content {
    height: 660px;
    overflow-y: auto;
}
</style>